package appmanager

import "gitee.com/huoyu123hk/cloudAgent/pkg/logx"

// UploadFile uploads a file to the server
func UploadFile(token, api string, filename string) {
	fm := NewFileManager(token, api)
	result := fm.UploadFile(filename)
	if result != "" {
		logx.Infof("File uploaded successfully: %s/api/sys/files/%s\n", api, result)
	}
}

// DownloadApp downloads the latest app for a project
func DownloadApp(token, api string, project string) {
	fm := NewFileManager(token, api)
	latestApps := fm.GetLatestVersion(project)
	if latestApps == nil {
		return
	}

	// 下载最新版本的应用
	for _, app := range latestApps {
		logx.Infof("应用包 %s 的最新版本: %s\n", app.Name, app.Version)
		filename := fm.Download(app.FileHash)
		if filename != "" {
			logx.Infof("应用包 %s 下载成功: %s\n", app.Name, filename)
			if fm.VerifyMD5(filename, app.FileHash) {
				logx.Infof("应用包 %s MD5 验证成功: %s\n", app.Name, filename)
			} else {
				logx.Errorf("应用包 %s MD5 验证失败: %s\n", app.Name, filename)
			}
		}
	}
}

func DeployApp(token, api string, project, name, version string, deployDir string, backupDir string) {
	fileManager := NewFileManager(token, api)
	app := fileManager.GetAppInfo(project, name)
	if app == nil {
		logx.Errorf("应用 %s 版本 %s 不存在", name, version)
		return
	}
	ad := NewAppDeploy(api, token, name, app.FileHash, backupDir, deployDir)
	if err := ad.Deploy(); err != nil {
		logx.Errorf("部署应用 %s 失败: %v", project, err)
	} else {
		logx.Infof("应用 %s 部署成功", project)
	}

}
